package com.apps.ftapp.fragment;


import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.afollestad.materialdialogs.MaterialDialog;
import com.apps.ftapp.R;
import com.apps.ftapp.activity.BookDetailActivity;
import com.apps.ftapp.activity.LessonDetailActivity;
import com.apps.ftapp.activity.NewSubjectActivity;
import com.apps.ftapp.activity.SubjectActivity;
import com.apps.ftapp.activity.SubjectMoreActivity;
import com.apps.ftapp.activity.TimeTableActivity;
import com.apps.ftapp.activity.ZhenTiNew2Activity;
import com.apps.ftapp.adapter.LessonNewAdapter;
import com.apps.ftapp.adapter.NewZpAdapter;
import com.apps.ftapp.bean.BookBean;
import com.apps.ftapp.bean.NewIndex;
import com.apps.ftapp.bean.ZhaopinBean;
import com.apps.ftapp.bean.ZigezhengBean;
import com.apps.ftapp.custom.NoScrollGridView;
import com.apps.ftapp.loader.GlideImageLoader;
import com.apps.ftapp.model.LessonModel;
import com.apps.ftapp.model.SubjectModel;
import com.apps.ftapp.model.TableModel;
import com.apps.ftapp.ui.ExamActivity;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.BroadCastManager;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.SharedPreferencesUtil;
import com.apps.ftapp.util.Tools;
import com.apps.ftapp.view.NoScrollListView;
import com.dou361.dialogui.DialogUIUtils;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cz.msebera.android.httpclient.Header;


public class NewHomeFragment extends Fragment {

    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.index_btn)
    TextView topTitle;
    @BindView(R.id.newRefreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.zpGridView)
    NoScrollGridView zpgridview;
    @BindView(R.id.mylinear)
    LinearLayout linearLayout;
    @BindView(R.id.lesson_listview)
    NoScrollListView listView;
    @BindView(R.id.main_scroll)
    ScrollView main_scroll;
    @BindView(R.id.main_rel)
    RelativeLayout time_rel;
    @BindView(R.id.zp_title)
    TextView zp_title;
    @BindView(R.id.book_title)
    TextView booktitle;
    @BindView(R.id.zp_more)
    TextView zp_more;
    @BindView(R.id.zp_img)
    TextView zp_img;
    @BindView(R.id.book_more)
    TextView book_more;
    @BindView(R.id.book_img)
    TextView book_img;
    @BindView(R.id.week_time)
    TextView week_time;


    @BindView(R.id.lin_model)
    LinearLayout lin1;
    @BindView(R.id.lin_weeknew)
    LinearLayout lin2;
    @BindView(R.id.lin_year)
    LinearLayout lin3;
    @BindView(R.id.lin_match)
    LinearLayout lin4;


    Unbinder unbinder;

    private LocalReceiver mReceiver;
    private NewIndex newIndex;//首页全部收据汇总
    private Gson gson = new Gson();
    private ImageLoader imageLoader = ImageLoader.getInstance();
    private DisplayImageOptions options;
    private String yiji_name;
    private MaterialDialog dialog;
    private int lessontype = 1;
    CallBack call;


    private String tempdata = "";


    //真题
    List<LessonModel.DataBean> lessonlist = new ArrayList<>();


    private NewZpAdapter zpAdapter;
    private LessonNewAdapter lessonNewAdapter;


    public NewHomeFragment() {

    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        call = (CallBack) getActivity();
        //接收广播
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction("fragment_home_left");
            mReceiver = new LocalReceiver();
            BroadCastManager.getInstance().registerReceiver(getActivity(),
                    mReceiver, filter);//注册广播接收者
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_new_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dorefresh();
                    }
                }, 1500);
            }
        });
        init();

        return view;

    }

    private void init() {
        refreshLayout.setEnableLoadMore(false);

        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setImageLoader(new GlideImageLoader());
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3500);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {

            }
        });
        yiji_name = SharedPreferencesUtil.getData(getContext(), "yijiName", "") + "";
        L.i("main", "yiji_name>>>>" + yiji_name);
        if (!"".equals(Tools.isNull(yiji_name))) {
            topTitle.setText(Tools.isNull(yiji_name));
        } else {
            topTitle.setText("自学考试");
        }
        if (null != dialog) {
            dialog.dismiss();
        }
        booktitle.setText("推荐图书");
        topTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                tanchuang();
            }
        });
        topTitle.setFocusable(true);
        topTitle.setFocusableInTouchMode(true);
        topTitle.requestFocus();

        if ("教师资格证".equals(yiji_name)) {
            lessontype = 1;
        } else {
            lessontype = 2;
        }

        zp_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                call.getData("教师资格证");
            }
        });
        zp_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                call.getData("教师资格证");
            }
        });

        book_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                call.getData("推荐图书");
            }
        });

        book_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                call.getData("推荐图书");
            }
        });

        lin1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), SubjectActivity.class);
                startActivity(intent);

            }
        });

        lin2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), NewSubjectActivity.class);
                startActivity(intent);
            }
        });

        lin3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), ZhenTiNew2Activity.class);
                intent.putExtra("flag", 2);
                startActivity(intent);
            }
        });

        lin4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), ZhenTiNew2Activity.class);
                intent.putExtra("flag", 1);
                startActivity(intent);
            }
        });

        zp_title.setText(yiji_name);
        List<ZigezhengBean> list = new ArrayList<>();
        zpAdapter = new NewZpAdapter(getActivity(), R.layout.fragment_index_listview_zigezheng_gridview_item, list);
        zpgridview.setAdapter(zpAdapter);


        List<LessonModel.DataBean> lessonlist = new ArrayList<>();
        lessonNewAdapter = new LessonNewAdapter(getActivity(), R.layout.fragment_lesson_listview_item, lessonlist);
        listView.setAdapter(lessonNewAdapter);


        time_rel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), TimeTableActivity.class);
                intent.putExtra("data", tempdata);
                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
            }
        });

        loaddata(1);


    }


    //加载首页数据  1初始载入 0刷新
    private void loaddata(final int type) {
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        Async.post("tiku/home", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", "<<<111111<<<<" + new String(responseBody) + "......");
                    try {
                        newIndex = gson.fromJson(new String(responseBody), NewIndex.class);
                        if (1 == Tools.isIntNull(newIndex.getSuccess())) {
                            final NewIndex.TanchuangBean tanchuangBean = newIndex.getTanchuang();
                            if (null != tanchuangBean && Tools.isNull(tanchuangBean.getIst()).equals("1")) {
                                View view = View.inflate(getActivity(), R.layout.view_location_dialog_dong, null);
                                ImageView imageView = view.findViewById(R.id.start_img);
                                imageLoader.displayImage(tanchuangBean.getImgurl(), imageView, options);
                                if (type > 0) {
                                    try {
                                        final Dialog dialog = DialogUIUtils.showCustomAlert(getActivity(), view).show();
                                        imageView.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                if (null != dialog)
                                                    dialog.dismiss();// 关闭弹出框
                                                if ("testpaper".equals(tanchuangBean.getType())) {
                                                    //字段 type为类型 当为“testpaper”的时候是模考广告，根据字段id 进入此模考页面
                                                    HashMap map = new HashMap();
                                                    map.put("id", tanchuangBean.getId());
                                                    ActivitySkipUtil.skipAnotherForActivity(getActivity(), ExamActivity.class, map);
                                                } else if ("course".equals(tanchuangBean.getType())) {
                                                    //当字段type为“course”的时候，是课程广告 ，根据字段id 进入此课程详情页
                                                    HashMap<String, Object> map = new HashMap();
                                                    map.put("id", tanchuangBean.getId());
                                                    map.put("title", "课程详情");
                                                    ActivitySkipUtil.skipAnotherActivity(getActivity(), LessonDetailActivity.class, map);
                                                } else if ("book".equals(tanchuangBean.getType())) {
                                                    //当字段type为“book”的时候，是图书广告 ，根据字段id 进入此图书详情页
                                                    HashMap<String, Object> params = new HashMap<>();
                                                    params.put("id", tanchuangBean.getId());
                                                    ActivitySkipUtil.skipAnotherActivity(getActivity(), BookDetailActivity.class, params);
                                                }
                                            }
                                        });
                                        Button mClose_btn = view.findViewById(R.id.btn_close);
                                        mClose_btn.setOnClickListener(new View.OnClickListener() {

                                            @Override
                                            public void onClick(View v) {
                                                dialog.dismiss();// 关闭弹出框
                                            }
                                        });
                                    } catch (Exception e) {
                                        e.printStackTrace();

                                    }
                                }
                            }
                            //成功之后的操作逻辑
                            getlesson(lessontype);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //加载数据
                    //loadZhenti();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }

    // 顶部banner图
    private void initBanner() {

        List<String> imgList = new ArrayList<>();
        for (String str : newIndex.getBanners()) {
            imgList.add(str);
        }
        banner.setImages(imgList);
        banner.start();
        initzp();
    }

    //教师资格证以及招聘推送
    private void initzp() {
        if (yiji_name.equals("教师资格证")) {
            zpAdapter.addAll(newIndex.getZigezheng());
        } else {
            List<ZigezhengBean> list = new ArrayList<>();
            for (int i = 0; i < newIndex.getZhaopin().size(); i++) {
                ZhaopinBean zhaopinBean = newIndex.getZhaopin().get(i);
                ZigezhengBean zigezhengBean = new ZigezhengBean();
                zigezhengBean.setId(zhaopinBean.getId());
                zigezhengBean.setLargePicture(zhaopinBean.getLargePicture());
                zigezhengBean.setPrice(zhaopinBean.getPrice());
                zigezhengBean.setStudentNum(zhaopinBean.getStudentNum());
                zigezhengBean.setTitle(zhaopinBean.getTitle());
                list.add(zigezhengBean);
            }
            zpAdapter.addAll(list);
        }
        initBook();

    }

    private void initBook() {
        linearLayout.removeAllViews();
        if (newIndex.getData().size() > 0) {
            for (final BookBean d : newIndex.getData()) {
                View view1 = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_index_scroll_item, null);
                ImageView imageView = view1.findViewById(R.id.book_img);
                TextView bookTitle = view1.findViewById(R.id.book_title);
                TextView bookShl = view1.findViewById(R.id.book_shl);
                imageLoader.displayImage(d.getLargePicture(), imageView, options);
                bookTitle.setText(d.getTitle());
                bookShl.setText(d.getSubtitle());
                view1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        HashMap map = new HashMap();
                        map.put("id", d.getId());
                        ActivitySkipUtil.skipAnotherForActivity(getActivity(), BookDetailActivity.class, map);

                    }
                });
                linearLayout.addView(view1);
            }
        }
        initLesson();
    }

    private void initLesson() {
        lessonNewAdapter.addAll(lessonlist);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                LessonModel.DataBean data = (LessonModel.DataBean) adapterView.getAdapter().getItem(i);
                HashMap<String, Object> map = new HashMap();
                map.put("id", data.getId());
                map.put("title", data.getTitle());
                //isFlag = false;
                ActivitySkipUtil.skipAnotherActivity(getActivity(), LessonDetailActivity.class, map);
            }
        });
    }

    private void tanchuang() {

        if (null != dialog) {
            dialog.dismiss();
        }
        dialog = new MaterialDialog.Builder(getActivity())
                .customView(R.layout.fragment_index_top, false)
                .show();


        View customeView = dialog.getCustomView();
        TextView quxiao = customeView.findViewById(R.id.quxiao);
        TextView queding = customeView.findViewById(R.id.queding);

        //
        TextView kaoshiVal = customeView.findViewById(R.id.kaoshi_val);
        TextView xueduanVal = customeView.findViewById(R.id.xueduan_val);
        TextView xuekeVal = customeView.findViewById(R.id.xueke_val);


        String yiji_name = SharedPreferencesUtil.getData(getContext(), "yijiName", "") + "";
        String erji_name = SharedPreferencesUtil.getData(getContext(), "erjiName", "") + "";
        String sanji_name = SharedPreferencesUtil.getData(getContext(), "sanjiName", "") + "";
        if (!"".equals(Tools.isNull(yiji_name))) {
            kaoshiVal.setText(Tools.isNull(yiji_name));
        } else {
            kaoshiVal.setText("自学考试");
        }
        if (!"".equals(Tools.isNull(erji_name))) {
            xueduanVal.setText(Tools.isNull(erji_name));
        } else {
            xueduanVal.setText(Tools.isNull("学前"));
        }
        if (!"".equals(Tools.isNull(sanji_name))) {
            xuekeVal.setText(Tools.isNull(sanji_name));
        } else {
            xuekeVal.setText(Tools.isNull("数学"));
        }

        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.hide();
            }
        });

        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != dialog) {
                    dialog.dismiss();
                }

                Constant.IS_EDIT_CHANAGE = "IndexFragment";

                ActivitySkipUtil.skipAnotherActivity(getActivity(), SubjectMoreActivity.class, false);
            }
        });
    }


    private void getlesson(int type) {
        RequestParams params = new RequestParams();
        params.put("categoryId", type);
        //params.put("zxueke", "");
        params.put("xueke", "");
        params.put("xueduan", "");
        params.put("leibie", "");
        params.put("page", 1);
        Async.get("course/explore", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                if (statusCode == 200) {
                    L.i("main", ":::::" + new String(responseBody));
                    LessonModel result = gson.fromJson(new String(responseBody), LessonModel.class);
                    if (null != result.getData()) {
                        lessonlist = result.getData();
//                        if (curPage == 1) {
//                            lessonAdapter.clear();
//                            lessonAdapter.notifyDataSetChanged();
//                        } else {
//
//                        }
//                        lessonAdapter.addAll(result.getData());
                        gettimetable();


                    }

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }

            @Override
            public void onFinish() {

                super.onFinish();
            }
        });
    }

    private void gettimetable() {
        RequestParams params = new RequestParams();
        params.add("userId", Constant.uid);
        params.add("token", Constant.token);
        Async.post("my/daycron", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    try {
                        Gson gson = new Gson();
                        TableModel result = gson.fromJson(new String(responseBody), TableModel.class);
                        //1表示红点，0表示灰点  //但是真实的数据时0红点 1灰点
                        if (1 == Tools.isIntNull(result.getSuccess())) {
                            if (!result.getLesson_date().equals("") && result.getLesson_date() != null) {
                                tempdata = result.getLesson_date();
                            }
                        }
                        getweekinfo();

                    } catch (Exception e) {

                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }


    private void getweekinfo() {

        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("page", 1);
        params.put("week", 1);
        Async.post("tiku/category", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody));
                    //SubjectModel
                    try {
                        SubjectModel result = gson.fromJson(new String(responseBody), SubjectModel.class);
                        if (1 == Tools.isIntNull(result.getSuccess())) {
                            if (null != result.getCategories() && result.getCategories().size() > 0) {
                                week_time.setText(result.getLast_create_day() + "更新");
                                initBanner();
                            }
                        }
                    } catch (Exception e) {

                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });

    }


    class LocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //收到广播后的处理
            dorefresh();

        }

    }


    private void dorefresh() {
        yiji_name = SharedPreferencesUtil.getData(getContext(), "yijiName", "") + "";
        L.i("main", "yiji_--------------name>>>>" + yiji_name);
        if (!"".equals(Tools.isNull(yiji_name))) {
            topTitle.setText(Tools.isNull(yiji_name));
        } else {
            topTitle.setText("自学考试");
        }
        if ("教师资格证".equals(yiji_name)) {
            lessontype = 1;
        } else {
            lessontype = 2;
        }
        zp_title.setText(yiji_name);
        newIndex = new NewIndex();
        lessonlist = new ArrayList<>();
        lessonNewAdapter.clear();
        zpAdapter.clear();
        loaddata(0);
        refreshLayout.finishRefresh();
    }


    public interface CallBack {
        void getData(String str);
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
    }
}
